package core.manager
{
import core.Language;
import core.StageProxy;
import core.model.GameModel;
import core.model.MapModel;
import core.model.PlayerModel;
import core.resources.LoadTaskBase;
import core.resources.ShopResourceTask;
import core.service.Service;
import core.service.ServiceRequest;

import flash.events.Event;

import mx.utils.StringUtil;

import values.common.CostValue;
import values.item.BuildingItemValue;
import values.item.IItemValue;
import values.item.INumbericItemValue;
import values.item.ItemValue;
import values.shop.ShopItemValue;

import view.component.dialog.AlertDialog;
import view.component.dialog.ConfirmDialog;
import view.component.window.MultipleBuyWindow;

/**
 * ShopManager
 * @author jliang
 *
 */
public class ShopManager
{    
    private static var currentShopItem:ShopItemValue;
    
    private static var currentBuyCount:int;
    
    private static var currentBuyCost:CostValue;
    
    private static var realItems:Vector.<IItemValue>;
    
    private static function get playerModel():PlayerModel
    {
        return GameModel.instance.playerModel;
    }
    
    private static function get mapModel():MapModel
    {
        return GameModel.instance.mapModel;
    }
    
    public static function requestToBuy(shopItem:ShopItemValue):void
    {
        if (shopItem.isBuildingItem ||
            shopItem.isEquipmentItem ||
            shopItem.hasCountLimit || 
            shopItem.totalRestNum <= 1)
        {
            //单个购买
            buy(shopItem);
        }
        else
        {
            //批量购买
            ConfirmDialog.show(shopItem, null, null, Language.getText("@multiple_buy_title_label"), Language.getText("@buy_button_label"), "", MultipleBuyWindow);
        }            
    }
    
    public static function buy(shopItem:ShopItemValue, count:int = 1):void
    {
        currentShopItem = shopItem;
        currentBuyCount = count;
        
        currentBuyCost = new CostValue();
        currentBuyCost.addItemValueObject(shopItem.costItemKey, Math.ceil(shopItem.nowCostNum * count));
        
        if (shopItem.isCashCost)
        {
            //购买RMB物品
            var str:String = StringUtil.substitute(Language.getText("@confirm_to_buy_desc"), 
                                                                        INumbericItemValue(currentBuyCost.costValueList[0]).num, 
                                                                        currentBuyCost.costValueList[0].name,
                                                                        shopItem.itemValue.name,
                                                                        count);            
            ConfirmDialog.show(str, yesToBuyWithCashHandler);
        }
        else
        {
            //购买非RMB物品
            if (hasSpaceToBuy(currentShopItem, currentBuyCount))
            {                
                var realItems:Vector.<IItemValue> = finalBuy(currentShopItem, currentBuyCount, currentBuyCost);
            }
            else
            {
                ConfirmDialog.show(Language.getText("@no_space_to_buy_desc"));
            }     
        }
    }
    
    private static function yesToBuyWithCashHandler():void
    {
        if (hasSpaceToBuy(currentShopItem, currentBuyCount))
        {
            var realItems:Vector.<IItemValue> = finalBuy(currentShopItem, currentBuyCount, currentBuyCost);
        }
        else
        {
            ConfirmDialog.show(Language.getText("@no_space_to_buy_desc"));
        }
    }
    
    private static function finalBuy(shopItem:ShopItemValue, count:int, cost:CostValue):Vector.<IItemValue>
    {
        StageProxy.lock();
        
        realItems = shopItem.generateItems(count);
        
        var buyRequest:ServiceRequest = new ServiceRequest("shop_buy", 
                                                                                                    [ shopItem.key, ItemValue.convertItemsToObjectArray(realItems), count ], 
                                                                                                    buyResponseHandler);            
        Service.invoke(buyRequest);
        
        return realItems;
    }
    
    private static function hasSpaceToBuy(shopItem:ShopItemValue, count:int):Boolean
    {
        var items:Vector.<IItemValue> = shopItem.generateItems(1);
        var item:IItemValue = items[0];
        if (shopItem.itemValue is INumbericItemValue)
        {
            INumbericItemValue(item).num = Math.ceil(INumbericItemValue(item).num * count);
        }
        return BonusManager.hasEoughSpaceToAddItemBonus(items);
    }
    
    private static function buyResponseHandler(data:Object):void
    {
        trace("Buy item flag: " + data.flag);
        switch (data.flag)
        {
            case 0:
                
                CostManager.cost(currentBuyCost);
                BonusManager.addItemBonus(realItems);
                
                //如果是建筑
                if (currentShopItem.isBuildingItem)
                {
                    var buildingItem:BuildingItemValue = realItems[0] as BuildingItemValue;
                    MapBuildingManager.create(buildingItem);
                    Game.instance.shopUI.close();
                }
                
                //购买成功
                if (currentShopItem.hasCountLimit || currentShopItem.hasDailyLimit)
                {
                    syncUpLimit();
                } 
                break;
            case 1:
                //购买失败, 商品已下架
                AlertDialog.show(Language.getText("@buy_fail_off_desc"));
                break;
            case 2:
                //购买失败, 当日购买数量已达上限
                AlertDialog.show(Language.getText("@buy_fail_no_rest_desc"));
                syncUpLimit();
                break;
            case 3:
                //购买失败, 没有库存了
                AlertDialog.show(Language.getText("@buy_fail_no_stock_desc"));
                syncUpLimit();
                break;
        }
        
        currentShopItem = null;
        currentBuyCost = null;
        currentBuyCount = 0;
        
        StageProxy.unlock();
    }
    
    private static var tasker:LoadTaskBase;
    
    public static function syncUpLimit():void
    {
        if (tasker)
        {
            return;
        }
        tasker = new ShopResourceTask();
        tasker.addEventListener(Event.COMPLETE, syncUpCompleteHandler);
        tasker.start();
    }
    
    private static function syncUpCompleteHandler(event:Event):void
    {
        tasker.removeEventListener(Event.COMPLETE, syncUpCompleteHandler);
        tasker.dispose();
        tasker = null;
    }
}
}





